package com.edu.juc.forkJoin;

import java.util.concurrent.RecursiveTask;

public class MyTask extends RecursiveTask<Integer> {
    // 拆分差值不能超过 10, 计算10以内运算
    private static final int VALUE = 10;
    private int start;
    private int end;
    private int result;

    // 拆分和合并过程
    @Override
    protected Integer compute() {
        if (end - start <= VALUE) {
            for (int i = start; i <= end; i++) {
                result += i;
            }
        } else { // 进一步拆分
            // 获取中间值
            int middle = (start + end) / 2;
            MyTask task01 = new MyTask(start, middle);
            task01.fork();
            MyTask task02 = new MyTask(middle + 1, end);
            task02.fork();

            // 合并结果
            result = task01.join() + task02.join();
        }
        return result;
    }

    public MyTask(int start, int end) {
        this.start = start;
        this.end = end;
    }
}
